//
//  WCNNewsVC.m
//  WCN
//
//  Created by wsj2015 on 15/11/1.
//  Copyright © 2015年 ShanghaiCize Trade And Business Co., Ltd. All rights reserved.
//

#import "WCNNewsVC.h"
#import "MJRefresh.h"
#import "WCPopupLayerManager.h"
#import "Macros.h"
#import "WCDefaultManager.h"
#import "WCNNewsDetailVC.h"
#import "WCItemTwoTabel_headView.h"
#import "WSJPickView.h"
#import "UITableView+(removeMjrefreshFooter).h"
#import "WCNewsListModel.h"
#import "WCNewListCell.h"
#import "WSJTableViewSelectAnimaton.h"
#import "UMMobClick/MobClick.h"
#import "Constants.h"

#define kNews_url @"http://www.hulijia360.com:8001/news/list.html"

@interface WCNNewsVC ()<UIWebViewDelegate,UITableViewDelegate,UITableViewDataSource>
{
    UIWebView *_webView;
    MBProgressHUD *_hud;
    NSString *_nurseId;
    NSString *_nurseName;
}
@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic,  strong) NSMutableArray *dataArray;

@property (nonatomic,  strong)  WCItemTwoTabel_headView *newsTagView;

//@property (nonatomic,  strong) WSJPickView *newsTagPicker;

@property (nonatomic, strong) NSString *flagName;

@property (nonatomic, assign) NSInteger page;
@property (nonatomic,  strong) WCNewListCell *selectedCell;

@end

@implementation WCNNewsVC

- (instancetype)init
{
    self = [super init];
    if (self) {
        self.page = 0;
    }
    return self;
}
- (UITableView *)tableView{
    if(!_tableView){
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 68, kScreenWidth, kScreenHeight-49-110) style:UITableViewStylePlain];
//        _tableView.backgroundColor = [UIColor redColor];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        [_tableView registerNib:[UINib nibWithNibName:@"WCNewListCell" bundle:nil] forCellReuseIdentifier:@"WCNewListCell"];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    }
    return _tableView;
}
- (NSMutableArray *)dataArray{
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;

}
//- (WSJPickView *)newsTagPicker{
//    if (!_newsTagPicker) {
//        _newsTagPicker  =[WSJPickView pickView];
//        _newsTagPicker.pickTitle = @"选择资讯类别";
//        
//    }
//    return _newsTagPicker;
//    
//}
- (WCItemTwoTabel_headView *)newsTagView{
    if (!_newsTagView) {
        _newsTagView =[[WCItemTwoTabel_headView alloc]initWithFrame:CGRectMake(0, 15, kScreenWidth, 50) withCatogoryArray:@[@"全部"]];
        _newsTagView.titleStr = @"资讯标签";
        
        __weak typeof(self) weakSelf =self;
        
        _newsTagView.catePickBlock =^(){
            [weakSelf getAllNewsTags];
            
        };
        
        _newsTagView.backgroundColor =[UIColor orangeColor] ;
    }
    return _newsTagView;
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = kAppBg;
    
    [self.view addSubview:self.newsTagView];
    [self.view addSubview:self.tableView];
    defineWeakSelf;
    [self.tableView addLegendHeaderWithRefreshingBlock:^{
        weakSelf.page = 0;
        [weakSelf getAllNewsListisRecover:YES];
    }];
    [self.tableView addLegendFooterWithRefreshingBlock:^{
        weakSelf.page++;
        [weakSelf getAllNewsListisRecover:NO];
        
    }];
    [self getAllNewsListisRecover:NO];
    
//    Account  *accout =[[WCDefaultManager shareMg] account];
//    _nurseId = accout.stringId;
//    _nurseName =accout.name;
//
//    _webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 20, kScreenWidth, kScreenHeight -64 -49)];
////    NSURLRequest *request =[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.baidu.com"]];
//    [self.view addSubview: _webView];
//    __weak typeof(self) weakSelf =self;
//    [self loadRequest];
//    _webView.delegate =self;
//    [_webView.scrollView addLegendHeaderWithRefreshingBlock:^{
//        [weakSelf loadRequest];
//        
//    }];
//    [webView loadRequest:request];
}
#pragma mark -获取所有资讯标签

- (void)getAllNewsTags{
    
    __weak typeof(self) weakSelf =self;
   
    [CoreSVP showSVPWithType:CoreSVPTypeLoadingInterface Msg:@"正在获取..." duration:0 allowEdit:YES beginBlock:nil completeBlock:nil];
    [[WCNetworkAccessManager sharedMg] POST:kGetAllNewsTag parameters:nil success:^(NSDictionary *responseObject) {
        NSMutableArray *dataArray =[NSMutableArray array];
        [dataArray addObject:@"全部"];
        if ([responseObject[@"data"] isKindOfClass:[NSArray class]]) {
            for (NSDictionary *dict in responseObject[@"data"]) {
                [dataArray addObject:dict[@"flagName"]];
            }
            WSJPickView *picker =[WSJPickView pickView];
            picker.pickTitle = @"选择资讯类别";
            picker.dataArray = dataArray;
            picker.saveBlock = ^(NSString *flagName,NSInteger index){
                weakSelf.flagName = flagName;
                weakSelf.newsTagView.btnTitle =[flagName isEqualToString:@"全部"]?@"全部":flagName;
                 weakSelf.page = 0;
                [weakSelf getAllNewsListisRecover:YES];
                
            };
            [picker show];
        }
        
    } failure:nil netError:^(id error) {
        
    } always:^{
        [CoreSVP dismiss];
    }];
    
    
}

#pragma -mark 请求新闻列表
-(void)getAllNewsListisRecover:(BOOL)isRecover
{
   
    //    page 页数  选填 默认 0
    //    rows 行数 选填 默认 10
    //    newsType 选填 (0
    NSMutableDictionary *params =[NSMutableDictionary dictionary];
    params[@"page"] = @(self.page);
    params[@"rows"] = @(10);
    params[@"newsType"] = @(1);
    if (_flagName) {
        params[@"flag"] = _flagName;
    }
    defineWeakSelf;
    [[WCNetworkAccessManager sharedMg] POST:kNewsList_part parameters:params success:^(NSDictionary *responseObject)
     {
         
         if (isRecover) {
             [weakSelf.dataArray removeAllObjects];
         }
         NSDictionary *dataDict =responseObject[@"data"];
         
         
         [UITableView remvoMJRefreshFooter:weakSelf.page totalPage:[dataDict[@"totalPages"] integerValue] forTableView:weakSelf.tableView withFootFreshBlock:^{
             ++weakSelf.page;
             [weakSelf getAllNewsListisRecover:NO];
         }];
         
         
         for (NSDictionary *dict in dataDict[@"content"]) {
             WCNewsListModel *model =[[WCNewsListModel alloc] init];
             [model setValuesForKeysWithDictionary:dict];
             [weakSelf.dataArray addObject:model];
         }
//         [weakSelf loadNOrecodView:weakSelf.tableView dataArray:_itemFourArray];
         [weakSelf.tableView reloadData];
       
       
         
     } failure:^(NSString *msg) {
         
     } netError:^(id error) {
         
     } always:^{
         [weakSelf.tableView.header endRefreshing];
         [weakSelf.tableView.footer endRefreshing];
     }];
    
    
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArray.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 120;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
   
    
    WCNewListCell *cell =[tableView dequeueReusableCellWithIdentifier:@"WCNewListCell" forIndexPath:indexPath];
    WCNewsListModel *model =self.dataArray[indexPath.row];
    cell.model = model;
    
    //    [cell configWithNewsListModel:model];
    return cell;

    
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    WCNewsListModel *model =self.dataArray[indexPath.row];
    
    WCNewListCell *cell = (WCNewListCell *)[self tableView:tableView cellForRowAtIndexPath:indexPath];
    self.selectedCell = cell;
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    weakSelf_define;
     [WSJTableViewSelectAnimaton excuteAnimationWithTableView:tableView withSuperView:self.view withCell:self.selectedCell withIndexPath:indexPath withCompleteBlock:^{
          [weakSelf jumpToNewsPageWithNewsId:[model.newsId integerValue]];
     }];
   
}

#pragma -mark 跳进网页的处理方法
- (void)jumpToNewsPageWithNewsId:(NSInteger)newsId
{
    
    Account *account =[[WCDefaultManager shareMg] account];
    ;
   
    NSString *name;
    if (account.name) {
        name =account.name;
    }else{
        name =@"匿名";
    }
    
    NSString *urlStr =[NSString stringWithFormat:@"%@?newsId=%i&commentby=nurse_%i&commentbyName=%@",kNewsDetail_url,newsId,[account.stringId integerValue],name];
    NSString * urlStrCode = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,(CFStringRef)urlStr,NULL,NULL,kCFStringEncodingUTF8));
#if DEBUG
    [[[UIAlertView alloc] initWithTitle:@"" message:urlStr delegate:self cancelButtonTitle:@"哦" otherButtonTitles:nil] show];

    
#else
    

#endif

    WCNNewsDetailVC *vc =[[WCNNewsDetailVC alloc] init];
    vc.url =[NSURL URLWithString:urlStrCode];
    //统计点击新闻
 
    [MobClick event:CheckNews];
    [self.navigationController pushViewController:vc animated:NO];
    
    
}

//
//- (void)refreshStateChange:(UIRefreshControl *)refreshC
//{
//    [self loadRequest];
//    
//    
//}
//- (void)loadRequest
//{
//    
//    NSURLRequest *request =[NSURLRequest requestWithURL:[NSURL URLWithString:kNews_url]];
//
//    [_webView loadRequest:request];
//}
//
//- (void)webViewDidFinishLoad:(UIWebView *)webView
//{
//    [[WCPopupLayerManager shareMg] showTextOnly:@"成功刷新最新数据" withView:self.view];
//    [webView.scrollView.header endRefreshing];
//    
//}
//- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
//{
//    NSLog(@"%@",request.URL.absoluteString);
//    if (![request.URL.absoluteString isEqualToString:kNews_url]) {
//        
////        NSLog(@"%@",request.URL);
//         NSString *newStr =[NSString stringWithFormat:@"%@&commentby=nurse_%@&commentbyName=%@",request.URL.absoluteString,_nurseId,_nurseName];
//        NSLog(@"%@",newStr);
//         NSString * encodedString1 = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,(CFStringRef)newStr,NULL,NULL,kCFStringEncodingUTF8));
//        WCNNewsDetailVC *nextVC = [[WCNNewsDetailVC alloc] init];
//        nextVC.url =[NSURL URLWithString:encodedString1];
//        
//        [self.navigationController pushViewController:nextVC animated:YES];
//        return NO;
//    }
//    return YES;
//
//}
//- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
//{
//    [_webView.scrollView.header endRefreshing];
//    [[WCPopupLayerManager shareMg] showTextOnly:error.localizedDescription withView:self.view];
//}




@end
